package org.sys.transporttrainsys.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.sys.transporttrainsys.entity.TrainingPlan;
import org.sys.transporttrainsys.service.TrainingPlanService;

import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping("/api/training-plans")
public class TrainingPlanController {

    @Autowired
    private TrainingPlanService trainingPlanService;

    @GetMapping
    public List<TrainingPlan> getAllTrainingPlans() {
        return trainingPlanService.getAllTrainingPlans();
    }

    @GetMapping("/{id}")
    public ResponseEntity<TrainingPlan> getTrainingPlanById(@PathVariable Long id) {
        TrainingPlan trainingPlan = trainingPlanService.getTrainingPlanById(id);
        if (trainingPlan != null) {
            return ResponseEntity.ok(trainingPlan);
        } else {
            return ResponseEntity.notFound().build(); // 返回404
        }
    }


    @PostMapping
    public TrainingPlan createTrainingPlan(@RequestBody TrainingPlan trainingPlan) {
        return trainingPlanService.createTrainingPlan(trainingPlan);
    }

    @PutMapping("/{id}")
    public ResponseEntity<TrainingPlan> updateTrainingPlan(@PathVariable Long id, @RequestBody TrainingPlan trainingPlan) {
        TrainingPlan updatedTrainingPlan = trainingPlanService.updateTrainingPlan(id, trainingPlan);
        if (updatedTrainingPlan != null) {
            return ResponseEntity.ok(updatedTrainingPlan);
        } else {
            return ResponseEntity.notFound().build(); // 返回404
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTrainingPlan(@PathVariable Long id) {
        trainingPlanService.deleteTrainingPlan(id);
        return ResponseEntity.noContent().build(); // 返回204
    }

    // 根据培训计划名称查询
    @GetMapping("/search/name")
    public List<TrainingPlan> searchTrainingPlansByName(@RequestParam String name) {
        return trainingPlanService.findByName(name);
    }


    // 根据类型查询
    @GetMapping("/search/type")
    public List<TrainingPlan> searchByType(@RequestParam String type) {
        return trainingPlanService.findByType(type);
    }

    // 根据名称和类型联合查询
    @GetMapping("/search")
    public List<TrainingPlan> searchByNameAndType(@RequestParam String name, @RequestParam String type) {
        return trainingPlanService.findByNameAndType(name, type);
    }
}